# for i in range():
#     try:
#         text = load_etext(args.etextno,
#                           mirror=args.mirror,
#                           prefer_ascii=args.prefer_ascii)
#         with reopen_encoded(args.outfile, 'w', 'utf8') as outfile:
#             outfile.write(text)
#     except Error as error:
#         parser.error(str(error))


# from gutenberg.query import list_supported_metadatas
# print(list_supported_metadatas())
# ('author', 'formaturi', 'language', 'rights', 'subject', 'title')

# from gutenberg.query import get_metadata
# print(get_metadata('title', 2701))  # prints frozenset([u'Moby Dick; Or, The Whale'])
# print(get_metadata('author', 2701)) # prints frozenset([u'Melville, Hermann'])

import logging
from http.client import HTTPConnection

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(pathname)s %(message)s')
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
HTTPConnection.debuglevel = 1

logging.debug('start')

import logging, sys
from urllib.request import HTTPHandler, HTTPSHandler, build_opener
hh = HTTPHandler()
hsh = HTTPSHandler()
hh.set_http_debuglevel(1)
hsh.set_http_debuglevel(1)
opener = build_opener(hh, hsh)
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.NOTSET)

from gutenberg.acquire import get_metadata_cache
cache = get_metadata_cache()
cache.populate()
# from gutenberg.acquire import set_metadata_cache
# from gutenberg.acquire.metadata import SqliteMetadataCache
# cache = SqliteMetadataCache('gutengbao.sqlite')
# logging.debug('cache ok ... 1')
# cache.populate()
# logging.debug('cache ok ... 2')
# set_metadata_cache(cache)
# logging.debug('cache ok ... 3')

from gutenberg.query import get_metadata
print(get_metadata('title', 2701))  # prints frozenset([u'Moby Dick; Or, The Whale'])
print(get_metadata('author', 2701)) # prints frozenset([u'Melville, Hermann'])

from gutenberg.query import get_etexts
print(get_etexts('title', 'Moby Dick; Or, The Whale'))  # prints frozenset([2701, ...])
print(get_etexts('author', 'Melville, Hermann'))        # prints frozenset([2701, ...])

# logging.debug(get_etexts('language', 'english'))

# from gutenberg.query.api import MetadataExtractor
# etexts = MetadataExtractor.get('language').get_etexts('english')
# list(etexts)
